﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using DiscoveryLogic.UI.Layouts.Converters;
using DiscoveryLogic.UI.Layouts.Models;
using DiscoveryLogic.UI.Layouts.Controls;
using System.Collections.Generic;
using DiscoveryLogic.DataServices.DataSources;

// using Slider = DiscoveryLogic.UI.Layouts.WrappedControls.Slider;

namespace DiscoveryLogic.UI.Layouts.ContentScreens
{

    public partial class RetirementPlanner : UserControl, IContentScreen
    {
        #region Private Variables

            MouseManager mouseEventManager;
            int currentStep = 1;
            int lastStep = 4;

            // Sliders
            //  Slider retirementAgeSlider;
            //  Slider planToAgeSlider;
            //Slider essentialExpensesSlider;
            //Slider discretionaryExpensesSlider;
            //Slider incomeSlider;
            //Slider homeEquitySlider;
            //Slider liquidAssetsSlider;
            // Slider investmentsSlider;
            //Slider riskToleranceSlider;
            //Slider resultsInvestSlider;
            //Slider resultsAgeSlider;
            //Slider resultsAmountSlider;

            DoubleCylinderBarGraph barGraph;

            // Retirement Plan
            DiscoveryLogic.UI.Layouts.Models.RetirementPlan plan;

            // For sample allocation screen
            PieChart sampleAllocationPie;
            int currentRiskTolerance = 1;
            List<FundLegend> fundLegendList;

            bool currentChartIsLine = true;

            DiscoveryLogic.UI.Layouts.Models.UserProfile userProfile;
            //TODO: this is a workaround for 
            bool _initializing = true;

        #endregion

        #region Constructors

            /// <summary>
            /// Initializes a new instance of the <see cref="RetirementPlanner"/> class.
            /// </summary>
            public RetirementPlanner()
            {
                // Required to initialize variables
                InitializeComponent();

                mouseEventManager = new MouseManager();

                plan = new DiscoveryLogic.UI.Layouts.Models.RetirementPlan();

                userProfile = DiscoveryLogic.UI.Layouts.Models.UserProfileManager.getUserProfile();

                fundLegendList = new List<FundLegend>();

                // Hook up events
                AttachHandlers();

                // Create bar graph in expense/income step
                barGraph = new DoubleCylinderBarGraph(0, 200000);
                barGraph.SetValue(Canvas.LeftProperty, 0.0);
                barGraph.SetValue(Canvas.TopProperty, 0.0);
                BarGraphsCanvas.Children.Add(barGraph);

                RetirementLineChart lc = new RetirementLineChart(plan);
                lc.SetValue(Canvas.TopProperty, 31.0);
                lc.SetValue(Canvas.LeftProperty, -18.0);
                rpLineChartCanvas.Children.Add(lc);
                
                BarChart bc = new BarChart(plan);
                rpBarChartCanvas.Children.Add(bc);                

                // Create Sample Allocation Pie Charts
                CreateSampleAllocationCharts();

                // Create Sliders
                CreateSliders();

                // Create fund legend for step 4 where we show sample pie charts
                CreateFundLegend();

                // Show the pie legend for the first sample pie chart in step 4
                OnAllocationScrollComplete(this, null);

                _initializing = false;
            }

        #endregion

        #region Public Methods

            public void FadeCanvasAnimation(bool show)
        {
            if (show == true)
            {
                FadeRetirementPlannerCanvasKeyFrame.Value = 1;
                FadeRetirementPlannerCanvas.Begin();
            }
            else
            {
                FadeRetirementPlannerCanvasKeyFrame.Value = 0;
                FadeRetirementPlannerCanvas.Begin();
            }
        }

        #endregion

        #region Helper Methods

            /// <summary>
            /// Create fundlegend objects for step 4 where we
            /// show sample allocation pie charts
            /// </summary>
            private void CreateFundLegend()
            {

                for (int i = 0; i < EnrollmentFund.numFundTypes; i++)
                {
                    fundLegendList.Add(new FundLegend((FundTypes)i, 50, 7));

                    if (i == 0 || i == 1 || i == 4)
                    {
                        fundLegendList[i].SetValue(Canvas.LeftProperty, 2695.276);
                    }
                    else
                    {
                        fundLegendList[i].SetValue(Canvas.LeftProperty, 2846.276);
                    }

                    if (i == 0 || i == 2)
                    {
                        fundLegendList[i].SetValue(Canvas.TopProperty, 281.174);
                    }
                    else if (i == 1 || i == 3)
                    {
                        fundLegendList[i].SetValue(Canvas.TopProperty, 321.174);
                    }
                    else
                    {
                        fundLegendList[i].SetValue(Canvas.TopProperty, 361.174);
                    }

                    rpSlidePanel.Children.Add(fundLegendList[i]);
                }
            }

            /// <summary>
            /// Creates the sample allocation pie charts.
            /// </summary>
            private void CreateSampleAllocationCharts()
            {
                for (int i = 0; i < 10; i++)
                {
                    double rpSampleAllocationCanvasLeft = (double)rpSampleAllocationCanvas.GetValue(Canvas.LeftProperty);
                    double rpSampleAllocationCanvasTop = (double)rpSampleAllocationCanvas.GetValue(Canvas.TopProperty);

                    sampleAllocationPie = new PieChart(new Point(150 + (360 * i), 100), 100, true, false);

                    // Determine allocation
                    switch (i)
                    {
                        case 0:
                            sampleAllocationPie.AddSlice(0.2, 0.2, new EnrollmentFund(0, FundTypes.ForeignBonds, "Fund E", 0, 0.2));
                            sampleAllocationPie.AddSlice(0.8, 0.8, new EnrollmentFund(1, FundTypes.DomesticBonds, "Fund B", 0, 0.8));
                            break;
                        case 1:
                            sampleAllocationPie.AddSlice(0.2, 0.2, new EnrollmentFund(0, FundTypes.ForeignBonds, "Fund E", 0, 0.2));
                            sampleAllocationPie.AddSlice(0.7, 0.7, new EnrollmentFund(1, FundTypes.DomesticBonds, "Fund B", 0, 0.7));
                            sampleAllocationPie.AddSlice(0.1, 0.1, new EnrollmentFund(2, FundTypes.DomesticEquity, "Fund X", 0, 0.1));
                            break;
                        case 2:
                            sampleAllocationPie.AddSlice(0.2, 0.2, new EnrollmentFund(0, FundTypes.ForeignBonds, "Fund E", 0, 0.2));
                            sampleAllocationPie.AddSlice(0.5, 0.5, new EnrollmentFund(1, FundTypes.DomesticBonds, "Fund B", 0, 0.5));
                            sampleAllocationPie.AddSlice(0.3, 0.3, new EnrollmentFund(2, FundTypes.DomesticEquity, "Fund X", 0, 0.3));
                            break;
                        case 3:
                            sampleAllocationPie.AddSlice(0.2, 0.2, new EnrollmentFund(0, FundTypes.ForeignBonds, "Fund E", 0, 0.2));
                            sampleAllocationPie.AddSlice(0.4, 0.4, new EnrollmentFund(1, FundTypes.DomesticBonds, "Fund B", 0, 0.4));
                            sampleAllocationPie.AddSlice(0.2, 0.2, new EnrollmentFund(2, FundTypes.DomesticEquity, "Fund X", 0, 0.2));
                            sampleAllocationPie.AddSlice(0.2, 0.2, new EnrollmentFund(3, FundTypes.ForeignEquity, "Fund Y", 0, 0.2));
                            break;
                        case 4:
                            sampleAllocationPie.AddSlice(0.2, 0.2, new EnrollmentFund(0, FundTypes.ForeignBonds, "Fund E", 0, 0.2));
                            sampleAllocationPie.AddSlice(0.2, 0.2, new EnrollmentFund(1, FundTypes.DomesticBonds, "Fund B", 0, 0.2));
                            sampleAllocationPie.AddSlice(0.3, 0.3, new EnrollmentFund(2, FundTypes.DomesticEquity, "Fund X", 0, 0.3));
                            sampleAllocationPie.AddSlice(0.3, 0.3, new EnrollmentFund(3, FundTypes.ForeignEquity, "Fund Y", 0, 0.3));
                            break;
                        case 5:
                            sampleAllocationPie.AddSlice(0.1, 0.1, new EnrollmentFund(0, FundTypes.ForeignBonds, "Fund E", 0, 0.1));
                            sampleAllocationPie.AddSlice(0.1, 0.1, new EnrollmentFund(1, FundTypes.DomesticBonds, "Fund B", 0, 0.1));
                            sampleAllocationPie.AddSlice(0.5, 0.5, new EnrollmentFund(2, FundTypes.DomesticEquity, "Fund X", 0, 0.5));
                            sampleAllocationPie.AddSlice(0.3, 0.3, new EnrollmentFund(3, FundTypes.ForeignEquity, "Fund Y", 0, 0.3));
                            break;
                        case 6:
                            sampleAllocationPie.AddSlice(0.1, 0.1, new EnrollmentFund(0, FundTypes.ForeignBonds, "Fund E", 0, 0.1));
                            sampleAllocationPie.AddSlice(0.4, 0.4, new EnrollmentFund(1, FundTypes.DomesticEquity, "Fund X", 0, 0.4));
                            sampleAllocationPie.AddSlice(0.5, 0.5, new EnrollmentFund(2, FundTypes.ForeignEquity, "Fund Y", 0, 0.5));
                            break;
                        case 7:
                            sampleAllocationPie.AddSlice(0.2, 0.2, new EnrollmentFund(0, FundTypes.ShortTerm, "Fund W", 0, 0.2));
                            sampleAllocationPie.AddSlice(0.4, 0.4, new EnrollmentFund(1, FundTypes.DomesticEquity, "Fund X", 0, 0.4));
                            sampleAllocationPie.AddSlice(0.4, 0.4, new EnrollmentFund(2, FundTypes.ForeignEquity, "Fund Y", 0, 0.4));
                            break;
                        case 8:
                            sampleAllocationPie.AddSlice(0.3, 0.3, new EnrollmentFund(0, FundTypes.ShortTerm, "Fund W", 0, 0.3));
                            sampleAllocationPie.AddSlice(0.3, 0.3, new EnrollmentFund(1, FundTypes.DomesticEquity, "Fund X", 0, 0.3));
                            sampleAllocationPie.AddSlice(0.4, 0.4, new EnrollmentFund(2, FundTypes.ForeignEquity, "Fund Y", 0, 0.4));
                            break;
                        case 9:
                            sampleAllocationPie.AddSlice(0.5, 0.5, new EnrollmentFund(0, FundTypes.ShortTerm, "Fund W", 0, 0.5));
                            sampleAllocationPie.AddSlice(0.2, 0.2, new EnrollmentFund(1, FundTypes.DomesticEquity, "Fund X", 0, 0.2));
                            sampleAllocationPie.AddSlice(0.3, 0.3, new EnrollmentFund(2, FundTypes.ForeignEquity, "Fund Y", 0, 0.3));
                            break;
                        default:
                            break;
                    }
                    sampleAllocationPie.SetValue(Canvas.NameProperty, "AllocationPie" + (i + 1));
                    sampleAllocationPie.DrawSlices();
                    sampleAllocationPie.HideFundIcons(true);
                    rpSampleAllocationCanvas.Children.Add(sampleAllocationPie);
                }
            }

            /// <summary>
            /// Attach event handlers to events.
            /// </summary>
            private void AttachHandlers()
            {
                mouseEventManager.changeStep += new MouseManager.NextStepEventHandler(OnNextScreen);

                //rpNextButtonOverlay.MouseEnter += mouseEventManager.OnMouseEnterHand;
                //rpNextButtonOverlay.MouseLeave += mouseEventManager.OnMouseLeaveArrow;
                //rpNextButtonOverlay.MouseLeftButtonDown += mouseEventManager.OnMouseClickNext;
                this.rpNextButton.Click += new RoutedEventHandler(mouseEventManager.OnMouseClickNext);

                //rpBackButtonOverlay.MouseEnter += mouseEventManager.OnMouseEnterHand;
                //rpBackButtonOverlay.MouseLeave += mouseEventManager.OnMouseLeaveArrow;
                //rpBackButtonOverlay.MouseLeftButtonDown += mouseEventManager.OnMouseClickBack;
                this.rpBackButton.Click += new RoutedEventHandler(mouseEventManager.OnMouseClickBack);

                //rpFinishButtonOverlay.MouseEnter += mouseEventManager.OnMouseEnterHand;
                //rpFinishButtonOverlay.MouseLeave += mouseEventManager.OnMouseLeaveArrow;
                //rpFinishButtonOverlay.MouseLeftButtonDown += new MouseButtonEventHandler(OnMouseClickFinish);
                this.rpFinishButton.Click += new RoutedEventHandler(OnMouseClickFinish);

                InvestmentsPopup.MouseEnter += new MouseEventHandler(OnPopupMouseEnter);
                InvestmentsPopup.MouseLeave += new MouseEventHandler(OnPopupMouseLeave);
                InvestmentsPopup.MouseEnter += mouseEventManager.OnMouseEnterHand;
                InvestmentsPopup.MouseLeave += mouseEventManager.OnMouseLeaveArrow;

                HomeEquityPopup.MouseEnter += new MouseEventHandler(OnPopupMouseEnter);
                HomeEquityPopup.MouseLeave += new MouseEventHandler(OnPopupMouseLeave);
                HomeEquityPopup.MouseEnter += mouseEventManager.OnMouseEnterHand;
                HomeEquityPopup.MouseLeave += mouseEventManager.OnMouseLeaveArrow;

                LiquidAssetsPopup.MouseEnter += new MouseEventHandler(OnPopupMouseEnter);
                LiquidAssetsPopup.MouseLeave += new MouseEventHandler(OnPopupMouseLeave);
                LiquidAssetsPopup.MouseEnter += mouseEventManager.OnMouseEnterHand;
                LiquidAssetsPopup.MouseLeave += mouseEventManager.OnMouseLeaveArrow;

                ChangeChartIcon.MouseEnter += mouseEventManager.OnMouseEnterHand;
                ChangeChartIcon.MouseLeave += mouseEventManager.OnMouseLeaveArrow;
                ChangeChartIcon.MouseLeftButtonUp += new MouseButtonEventHandler(OnChangeChartClick);

                ChangeChartArrow.MouseEnter += mouseEventManager.OnMouseEnterHand;
                ChangeChartArrow.MouseLeave += mouseEventManager.OnMouseLeaveArrow;
                ChangeChartArrow.MouseLeftButtonUp += new MouseButtonEventHandler(OnChangeChartClick);

                // Set handlers for popping up tip on hover over of question marks

                // For essential Question Mark
                EssentialExpensesQuestionMark.MouseEnter += new MouseEventHandler(OnQuestionMarkMouseEnter);
                EssentialExpensesQuestionMark.MouseLeave += new MouseEventHandler(OnQuestionMarkMouseLeave);

                DiscretionaryExpensesQuestionMark.MouseEnter += new MouseEventHandler(OnQuestionMarkMouseEnter);
                DiscretionaryExpensesQuestionMark.MouseLeave += new MouseEventHandler(OnQuestionMarkMouseLeave);

                IncomeQuestionMark.MouseEnter += new MouseEventHandler(OnQuestionMarkMouseEnter);
                IncomeQuestionMark.MouseLeave += new MouseEventHandler(OnQuestionMarkMouseLeave);
            }

            void rpNextButton_Click(object sender, RoutedEventArgs e)
            {
                throw new NotImplementedException();
            }

            /// <summary>
            /// Creates the sliders.
            /// </summary>
            private void CreateSliders()
            {
                // Get default values from WS
                DiscoveryLogic.UI.Layouts.Models.SliderDefaults sliderDefaults = DiscoveryLogic.UI.Layouts.Models.SliderDefaultsManager.getSliderDefaults();


                //JAIMERTODP1: Order matters...  :( 
                // Not sure what order is so create all sliders first.. 

                //                planToAgeSlider = NewSlider(sliderDefaults.PlannerPlanToAgeMin, sliderDefaults.PlannerPlanToAgeMax, -40, 63.5);
                //retirementAgeSlider = NewSlider(sliderDefaults.PlannerRetirementAgeMin, sliderDefaults.PlannerRetirementAgeMax, -40, 0.5);
                //essentialExpensesSlider = NewSlider(sliderDefaults.PlannerEssExpenesesMin, sliderDefaults.PlannerEssExpenesesMax, 718.779, -0.5);
                //discretionaryExpensesSlider = NewSlider(sliderDefaults.PlannerDisExpenesesMin, sliderDefaults.PlannerDisExpenesesMax, 718.779, 58.5);
                //incomeSlider = NewSlider(sliderDefaults.PlannerIncomeMin, sliderDefaults.PlannerIncomeMax, 718.779, 130.499);
                //homeEquitySlider = NewSlider(sliderDefaults.PlannerHomeEquityMin, sliderDefaults.PlannerHomeEquityMax, 1478.279, 0.5);
                //liquidAssetsSlider = NewSlider(sliderDefaults.PlannerLiquidAssetsMin, sliderDefaults.PlannerLiquidAssetsMax, 1478.279, 59.5);
                //riskToleranceSlider = NewSlider(1, 10, 2230.443, 3.5);
                //resultsAgeSlider = NewSlider(sliderDefaults.PlannerRetirementAgeMin, sliderDefaults.PlannerRetirementAgeMax, 3403.443, 147.5);
                //resultsInvestSlider = NewSlider(1, 10, 3403.443, 85.5);
                //resultsAmountSlider = NewSlider(0, 100, 3403.443, 209.5);


                planToAgeSlider.Minimum = sliderDefaults.PlannerPlanToAgeMin;
                planToAgeSlider.Maximum = sliderDefaults.PlannerPlanToAgeMax;


                retirementAgeSlider.Minimum = sliderDefaults.PlannerRetirementAgeMin;
                retirementAgeSlider.Maximum = sliderDefaults.PlannerRetirementAgeMax;

                essentialExpensesSlider.Minimum = sliderDefaults.PlannerEssExpenesesMin;
                essentialExpensesSlider.Maximum = sliderDefaults.PlannerEssExpenesesMax;
                discretionaryExpensesSlider.Minimum = sliderDefaults.PlannerDisExpenesesMin;
                discretionaryExpensesSlider.Maximum = sliderDefaults.PlannerDisExpenesesMax;
                incomeSlider.Minimum = sliderDefaults.PlannerIncomeMin;
                incomeSlider.Maximum = sliderDefaults.PlannerIncomeMax;

                homeEquitySlider.Minimum = sliderDefaults.PlannerHomeEquityMin;
                homeEquitySlider.Maximum = sliderDefaults.PlannerHomeEquityMax;
                liquidAssetsSlider.Minimum = sliderDefaults.PlannerLiquidAssetsMin;
                liquidAssetsSlider.Maximum = sliderDefaults.PlannerLiquidAssetsMax;
                investmentsSlider.Minimum = sliderDefaults.PlannerInvestmentsMin;
                investmentsSlider.Maximum = sliderDefaults.PlannerInvestmentsMax;

                riskToleranceSlider.Minimum = 1;
                riskToleranceSlider.Maximum = 10;
                

                resultsAgeSlider.Minimum = sliderDefaults.PlannerRetirementAgeMin;
                resultsAgeSlider.Maximum = sliderDefaults.PlannerRetirementAgeMax;
                
                resultsInvestSlider.Minimum = 1;
                resultsInvestSlider.Maximum = 10;

                resultsAmountSlider.Minimum = 0;
                resultsAmountSlider.Maximum = 100;

                retirementAgeSlider.Value = sliderDefaults.PlannerRetirementAgeDefault;
                planToAgeSlider.Value = sliderDefaults.PlannerPlanToAgeDefault;


                OnSliderMoved(retirementAgeSlider, null);
                OnSliderMoved(planToAgeSlider, null);

                essentialExpensesSlider.Value = sliderDefaults.PlannerEssExpenesesDefault;
                OnSliderMoved(essentialExpensesSlider, null);

                discretionaryExpensesSlider.Value = sliderDefaults.PlannerDisExpenesesDefault;
                discretionaryExpensesSlider.SetValue(Canvas.ZIndexProperty, 3);
                OnSliderMoved(discretionaryExpensesSlider, null);


                incomeSlider.Value = (sliderDefaults.PlannerIncomeDefault);
                OnSliderMoved(incomeSlider, null);

                homeEquitySlider.Value = (sliderDefaults.PlannerHomeEquityDefault);

                liquidAssetsSlider.Value = (sliderDefaults.PlannerLiquidAssetsDefault);


                investmentsSlider.Value = (sliderDefaults.PlannerInvestmentsDefault);

                OnSliderMoved(homeEquitySlider, null);
                OnSliderMoved(liquidAssetsSlider, null);
                OnSliderMoved(investmentsSlider, null);

                riskToleranceSlider.Value = (userProfile.RiskTolerance);
                OnSliderMoved(riskToleranceSlider, null);


                OnSliderMoved(resultsInvestSlider, null);

                OnSliderMoved(retirementAgeSlider, null);


                resultsAmountSlider.Value = userProfile.ContributionAmount;
                OnSliderMoved(resultsAmountSlider, null);
            }

            /*
            private Slider NewSlider(double minValue, double maxValue, double left, double top)
            {
                System.Diagnostics.Debug.Assert(false, "DELETE THIS CODE, ALL SLIDERS SHOULD BE DONE FROM xaml");
                Slider newSlider = new Slider(minValue, maxValue);
                newSlider.SetValue(Canvas.LeftProperty, left + 45);
                newSlider.SetValue(Canvas.TopProperty, top + 85);
                newSlider.Width = 287;
                newSlider.Height = 20;

                newSlider.ValueChanged += new RoutedPropertyChangedEventHandler<double>(OnSliderMoved);
                rpSlidePanel.Children.Add(newSlider);


                return newSlider;
            }*/ 


            private void UpdateTotalAssets()
            {
                double totalAssets = homeEquitySlider.Value +
                                         liquidAssetsSlider.Value +
                                         investmentsSlider.Value;
                TotalAssetsTextBlock.Text = "Total: " + Convert.ToInt32(totalAssets).ToCurrency();
            }

        #endregion

        #region Event Handler

            private void OnAllocationScrollComplete(object sender, EventArgs e)
            {

                PieChart currentAllocation = (PieChart)rpSampleAllocationCanvas.FindName("AllocationPie" + currentRiskTolerance);
                FundTypes[] fundTypes = currentAllocation.GetSliceFundTypes();

                for (int i = 0; i < EnrollmentFund.numFundTypes; i++)
                {
                    fundLegendList[i].Opacity = 0;
                }

                for (int i = 0; i < fundTypes.Length; i++)
                {
                    fundLegendList[i].SwitchFundType(fundTypes[i]);
                    fundLegendList[i].Opacity = 1;
                }

            }


            /// <summary>
            /// Called when [scroll complete].
            /// </summary>
            /// <param name="sender">The sender.</param>
            /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
            private void OnScrollComplete(object sender, EventArgs e)
            {
                // If last step, make "Next" button invisible
                if (currentStep == lastStep)
                {
                    //JAIMERTODOP0 ... bug.. how to get around it ?? 
                    // rpNextButton.Visibility = Visibility.Collapsed;
                    rpFinishButton.Visibility = Visibility.Visible;
                    SetVisibleUsingWorkaround(rpNextButton, false);
                    SetVisibleUsingWorkaround(rpFinishButton, true);

                    // Make sure Line and Bar charts on last results screen is hidden
                    // because if not, its edges will peep out on the previous screen.
                    // Only shown when "Finish" button is clicked
                    rpLineChartCanvas.Opacity = 0;
                    rpBarChartCanvas.Opacity = 0;
                }
                else if (!(currentStep == lastStep + 1))
                {
                    rpNextButton.Visibility = Visibility.Visible;
                    //rpFinishButton.Visibility = Visibility.Collapsed;
                    SetVisibleUsingWorkaround(rpNextButton, true);
                    SetVisibleUsingWorkaround(rpFinishButton, false);
                }
                else // currentStep == lastStep +1 ) 
                {
                    SetVisibleUsingWorkaround(rpNextButton, false);
                    SetVisibleUsingWorkaround(rpFinishButton, false);

                    // TODO: For now as a workaround, we call this method 
                    // again because sometimes, rendering the linechart fails
                    // and we have an empty line chart.  On the second render, it always
                    // seems to be fine.
                    OnMouseClickFinish(this, new RoutedEventArgs());

                    rpLineChartCanvas.Opacity = 1;
                    rpBarChartCanvas.Opacity = 1;
                }

                // If not first step, then make "Previous" button visible
                if (currentStep != 1)
                {
                    rpBackButton.Visibility = Visibility.Visible;
                    SetVisibleUsingWorkaround(rpBackButton, true);
                }
                else
                {
                    //  rpBackButton.Visibility = Visibility.Collapsed;
                    SetVisibleUsingWorkaround(rpBackButton, false);
                }

            }

            public void SetVisibleUsingWorkaround(System.Windows.Controls.Button btn, bool visibility)
            {
                if (visibility)
                {
                    btn.Opacity = 1.0;
                    btn.SetValue(Canvas.ZIndexProperty, 5);
                }
                else
                {
                    btn.Opacity = 0.0;
                    btn.SetValue(Canvas.ZIndexProperty, 0);
                }

            }

            /// <summary>
            /// When a slider in retirement planner is moved an event
            /// is fired and this method catches it.
            /// Updates textboxes and labels based on the slider movement.
            /// </summary>
            /// <param name="sender">The sender.</param>
            /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
            private void OnSliderMoved(object sender, RoutedPropertyChangedEventArgs<double> e)
            {
                System.Windows.Controls.Slider slider = (System.Windows.Controls.Slider)sender;
                int currentValue = Convert.ToInt32(slider.Value);

                if (sender == retirementAgeSlider)
                {
                    RetirementAgeTextBlock.Text = currentValue.ToString();

                    // Check if age is > planned age
                    if (currentValue > Convert.ToInt32(planToAgeSlider.Value))
                    {
                        planToAgeSlider.Value = (currentValue);
                        PlanToAgeTextBlock.Text = Convert.ToInt32(planToAgeSlider.Value).ToString();
                    }
                }
                else if (sender == planToAgeSlider)
                {
                    PlanToAgeTextBlock.Text = currentValue.ToString();

                    // Check if age is > planned age
                    if (currentValue < Convert.ToInt32(retirementAgeSlider.Value))
                    {
                        retirementAgeSlider.Value = (currentValue);
                        RetirementAgeTextBlock.Text = Convert.ToInt32(retirementAgeSlider.Value).ToString();
                    }
                }
                else if (sender == essentialExpensesSlider)
                {
                    EssentialExpensesTextBlock.Text = currentValue.ToCurrency();
                    barGraph.Bar3Value = currentValue;
                }
                else if (sender == discretionaryExpensesSlider)
                {
                    DiscretionaryExpensesTextBlock.Text = currentValue.ToCurrency();
                    barGraph.Bar2Value = currentValue;
                }
                else if (sender == incomeSlider)
                {
                    IncomeTextBlock.Text = currentValue.ToCurrency();
                    barGraph.Bar1Value = currentValue;
                }
                else if (sender == homeEquitySlider)
                {
                    HomeEquityTextBlock.Text = currentValue.ToCurrency();
                    UpdateTotalAssets();
                }
                else if (sender == liquidAssetsSlider)
                {
                    LiquidAssetsTextBlock.Text = currentValue.ToCurrency();
                    UpdateTotalAssets();
                }
                else if (sender == investmentsSlider)
                {
                    InvestmentsTextBlock.Text = currentValue.ToCurrency();
                    UpdateTotalAssets();
                }
                else if (sender == riskToleranceSlider)
                {
                    // Set textblock to the correct risk tolerance level
                    rpRiskToleranceLabelFrame.Width = 137.333;
                    rpRiskToleranceLabel.Text = AppResources.GetRiskLevelString(currentValue);

                    if (currentValue == 7)
                    {
                        rpRiskToleranceLabelFrame.Width = 180;
                    }
                    else if (currentValue == 4)
                    {
                        rpRiskToleranceLabelFrame.Width = 160;
                    }

                    // Change sample allocation chart
                    if (currentValue != currentRiskTolerance)
                    {
                        rpAllocationCanvasScrollKeyFrame.Value = -1 * ((sampleAllocationPie.Radius * 2 + 160) * (currentValue - 1));
                        try
                        {
                            rpAllocationCanvasScroll.Begin();
                        }
                        catch  
                        {
                            rpSampleAllocationCanvas.SetValue(Canvas.LeftProperty, -1 * ((sampleAllocationPie.Radius * 2 + 160) * (currentValue - 1)));
                        }

                        // Hide description of old style
                        TextBlock styleDescript = (TextBlock)RetirementPlannerCanvas.FindName("rpInvestmentStyle" + currentRiskTolerance + "Descript");
                        styleDescript.Opacity = 0;
                        // Show description of new style
                        styleDescript = (TextBlock)RetirementPlannerCanvas.FindName("rpInvestmentStyle" + currentValue + "Descript");
                        styleDescript.Opacity = 1;

                        // Update value
                        currentRiskTolerance = currentValue;
                    }
                }
                else if (sender == resultsAgeSlider)
                {
                    //JAIMERTODOP0 System.Diagnostics.Debug.Assert(false, "fix this later"); 
                    //if (!this._initializing)
                    //{
                        plan.RetirementAge = currentValue;
                        rpResultsAgeTextBlock.Text = plan.RetirementAge.ToString();
                        plan.RecalculatePlan();
                    //}
                }
                else if (sender == resultsAmountSlider)
                {
                    plan.ContributionPercent = currentValue / 100.00;
                    rpResultsContributionTextBlock.Text = ((double)currentValue / 100.00).ToPercentage();
                    plan.RecalculatePlan();
                }
                else if (sender == resultsInvestSlider)
                {
                    plan.InvestmentStyle = currentValue;

                    // Set textblock to the correct risk tolerance level
                    rpResultsRiskTextBlock.Text = AppResources.GetRiskLevelString(currentValue);

                    if (currentValue == 7)
                    {
                        rpResultsRiskTextBlockFrame.SetValue(Canvas.LeftProperty, 3560.139);
                        rpResultsRiskTextBlock.SetValue(Canvas.LeftProperty, 3571.294);
                        rpResultsRiskTextBlockFrame.Width = 180;
                    }
                    else if (currentValue == 4)
                    {
                        rpResultsRiskTextBlockFrame.SetValue(Canvas.LeftProperty, 3575.139);
                        rpResultsRiskTextBlock.SetValue(Canvas.LeftProperty, 3586.294);
                        rpResultsRiskTextBlockFrame.Width = 160;
                    }
                    else
                    {
                        rpResultsRiskTextBlockFrame.Width = 137.333;
                        rpResultsRiskTextBlockFrame.SetValue(Canvas.LeftProperty, 3597.806);
                        rpResultsRiskTextBlock.SetValue(Canvas.LeftProperty, 3608.961);
                    }

                    plan.RecalculatePlan();
                }
            }

            /// <summary>
            /// When the user clicks the Finish button, get the values
            /// of all the sliders and put it into the retirement plan
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void OnMouseClickFinish(object sender, RoutedEventArgs e)
            {
        


                plan.RetirementAge = (int)retirementAgeSlider.Value;
                resultsAgeSlider.Value = plan.RetirementAge;
                OnSliderMoved(resultsAgeSlider, null);

                plan.PlanToAge = (int)planToAgeSlider.Value;

                plan.AnnualEssentialExpenses = essentialExpensesSlider.Value;

                plan.AnnualDiscretionaryExpenses = discretionaryExpensesSlider.Value;

                plan.AnnualIncome = incomeSlider.Value;

                plan.HomeEquity = homeEquitySlider.Value;

                plan.LiquidAssets = liquidAssetsSlider.Value;

                plan.Investments = investmentsSlider.Value;

                plan.InvestmentStyle = (int)riskToleranceSlider.Value;

                plan.ContributionAmount = userProfile.ContributionAmount;

                // Save to user profile
                userProfile.RiskTolerance = plan.InvestmentStyle;

                resultsInvestSlider.Value = (plan.InvestmentStyle);
                OnSliderMoved(resultsInvestSlider, null);

                // Set contribution slider value based on profile
                resultsAmountSlider.Value = userProfile.ContributionAmount;
                OnSliderMoved(resultsAmountSlider, null);

                // Recalculate the retirement plan based on new numbers
                plan.RecalculatePlan();

                // Shrink/Grow the charts
                rpLineChartCanvas.Opacity = 1;
                rpBarChartCanvas.Opacity = 1;

                BarChartShrink.Begin();
                LineChartGrow.Begin();
                currentChartIsLine = true;

                // Raise event to slide to next screen
                DiscoveryLogic.UI.Layouts.Models.CustomEventArgs args = new DiscoveryLogic.UI.Layouts.Models.CustomEventArgs();
                args.NextStep = true;
                OnNextScreen(this, args);

                // Start the throbbing animation of the change chart arrow in the last step                
                //ChangeChartArrowThrob.Begin();
            }

            /// <summary>
            /// Called when [next screen].
            /// </summary>
            /// <param name="sender">The sender.</param>
            /// <param name="e">The <see cref="WoodgroveInvestments.Models.CustomEventArgs"/> instance containing the event data.</param>
            private void OnNextScreen(object sender, DiscoveryLogic.UI.Layouts.Models.CustomEventArgs e)
            {
                // Stop throbbing arrow animation on the last screen if its playing
                //ChangeChartArrowThrob.Stop();

                if (e.NextStep == true && rpNextButton.Opacity == 0 && rpFinishButton.Opacity == 0 ||
                    e.NextStep == false && rpBackButton.Opacity == 0)
                {
                    return;
                }                

                // Get current position of slider panel
                double leftPosition = (double)rpSlidePanel.GetValue(Canvas.LeftProperty);

                // Determine which direction we are scrolling
                if (e.NextStep)
                {
                    rpScrollSlidePanelKeyFrame.Value = leftPosition - 760;

                    // If we're going to step 4 from step 3
                    if (currentStep == 3)
                    {
                        riskToleranceSlider.Value = (userProfile.RiskTolerance);
                        OnSliderMoved(riskToleranceSlider, null);
                    }

                    // Increment the variable that keeps track of what step we are in
                    TextBlock tb = (TextBlock)RetirementPlannerCanvas.FindName("rpStep" + currentStep + "Label");
                    if (tb != null)
                    {
                        tb.Opacity = 0.3;
                    }

                    currentStep++;

                    tb = (TextBlock)RetirementPlannerCanvas.FindName("rpStep" + currentStep + "Label");
                    if (tb != null)
                    {
                        tb.Opacity = 1;
                    }
                }
                else
                {
                    rpScrollSlidePanelKeyFrame.Value = leftPosition + 760;

                    // Decrement the variable that keeps track of what step we are in
                    TextBlock tb = (TextBlock)RetirementPlannerCanvas.FindName("rpStep" + currentStep + "Label");
                    if (tb != null)
                    {
                        tb.Opacity = 0.3;
                    }

                    currentStep--;

                    tb = (TextBlock)RetirementPlannerCanvas.FindName("rpStep" + currentStep + "Label");
                    if (tb != null)
                    {
                        tb.Opacity = 1;
                    }


                }

                // Hide buttons

                //JAIMERTODOP0 ....   The three lines below were commented out as there appears to be a problem 
                // with buttons on 2/15 build.
                // Still causes problem on 2/21 build.
                //rpNextButton.Visibility = Visibility.Collapsed;
                //rpBackButton.Visibility = Visibility.Collapsed;
                //rpFinishButton.Visibility = Visibility.Collapsed;

                SetVisibleUsingWorkaround(rpNextButton, false);
                SetVisibleUsingWorkaround(rpBackButton, false);
                SetVisibleUsingWorkaround(rpFinishButton, false);
                
                // Start scroll animation
                rpScrollSlidePanel.Begin();
            }

            private void OnPopupMouseEnter(object sender, MouseEventArgs e)
            {
                if (sender == HomeEquityPopup)
                {
                    rpQuestionMarkPopupText.Text = (string)Resources["Res_HomeEquityPopup"];
                    rpQuestionMarkPopup.SetValue(Canvas.TopProperty, (double)HomeEquityPopup.GetValue(Canvas.TopProperty) - 85);
                }
                else if (sender == LiquidAssetsPopup)
                {
                    rpQuestionMarkPopupText.Text = (string)Resources["Res_LiquidAssetsPopup"];
                    rpQuestionMarkPopup.SetValue(Canvas.TopProperty, (double)LiquidAssetsPopup.GetValue(Canvas.TopProperty) - 85);
                }
                else if (sender == InvestmentsPopup)
                {
                    rpQuestionMarkPopupText.Text = (string)Resources["Res_InvestmentsPopup"];
                    rpQuestionMarkPopup.SetValue(Canvas.TopProperty, (double)InvestmentsPopup.GetValue(Canvas.TopProperty) - 85);
                }
                else
                {
                    return;
                }

                rpQuestionMarkPopup.Visibility = Visibility.Visible;

            }

            private void OnPopupMouseLeave(object sender, MouseEventArgs e)
            {
                rpQuestionMarkPopup.Visibility = Visibility.Collapsed;
            }

            private void OnChangeChartClick(object sender, MouseButtonEventArgs e)
            {
                ChangeChartArrowRotateKeyFrame.Value += -360;
                ChangeChartArrowRotate.Begin();

                if (currentChartIsLine)
                {
                    BarChartGrow.Begin();
                    LineChartShrink.Begin();
                    currentChartIsLine = false;
                }
                else
                {
                    BarChartShrink.Begin();
                    LineChartGrow.Begin();
                    currentChartIsLine = true;
                }
            }

            private void OnQuestionMarkMouseEnter(object sender, MouseEventArgs e)
            {
                if (sender == IncomeQuestionMark)
                {
                    IncomeQuestionMarkPopup.Visibility = Visibility.Visible;
                }
                else if (sender == DiscretionaryExpensesQuestionMark)
                {
                    DiscretionaryExpensesQuestionMarkPopup.Visibility = Visibility.Visible;
                }
                else if (sender == EssentialExpensesQuestionMark)
                {
                    EssentialExpensesQuestionMarkPopup.Visibility = Visibility.Visible;
                }
            }

            private void OnQuestionMarkMouseLeave(object sender, MouseEventArgs e)
            {
                if (sender == IncomeQuestionMark)
                {
                    IncomeQuestionMarkPopup.Visibility = Visibility.Collapsed;
                }
                else if (sender == DiscretionaryExpensesQuestionMark)
                {
                    DiscretionaryExpensesQuestionMarkPopup.Visibility = Visibility.Collapsed;
                }
                else if (sender == EssentialExpensesQuestionMark)
                {
                    EssentialExpensesQuestionMarkPopup.Visibility = Visibility.Collapsed;
                }
            }

        #endregion

        #region IContentScreen Members

            public void ScreenShowActions()
            {
                // Hide charts
                rpLineChartCanvas.Opacity = 0;
                rpBarChartCanvas.Opacity = 0;
            }

            public void ScreenHideActions()
            {
                // Reset screen
                rpSlidePanel.SetValue(Canvas.LeftProperty, 75.0);
                                
                SetVisibleUsingWorkaround(rpNextButton, true);
                SetVisibleUsingWorkaround(rpBackButton, false);
                SetVisibleUsingWorkaround(rpFinishButton, false);

                // Reset header step labels
                // Increment the variable that keeps track of what step we are in
                TextBlock tb = (TextBlock)RetirementPlannerCanvas.FindName("rpStep" + currentStep + "Label");
                
                if (tb != null)
                {
                    tb.Opacity = 0.3;
                }

                currentStep = 1;

                tb = (TextBlock)RetirementPlannerCanvas.FindName("rpStep" + currentStep + "Label");
                
                if (tb != null)
                {
                    tb.Opacity = 1;
                }
            }

        #endregion
    }
}
